package com.imau.common.filter;

import com.imau.service.UserService;
import com.imau.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "ApplicationFilter", urlPatterns = "/*")
public class ApplicationFilter implements Filter {

    private UserService userService;

    public void init(FilterConfig config) throws ServletException {
        userService = new UserServiceImpl();
    }

    public void destroy() {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //设置统一编码
        httpResponse.setCharacterEncoding("utf-8");
        httpRequest.setCharacterEncoding("utf-8");
        httpResponse.setContentType("text/json;charset=utf-8");

        //1. 获取请求的URI
     //   String requestURI = httpRequest.getRequestURI();

        //2. 截取
     //   int index = requestURI.lastIndexOf("/");

    //    String method = requestURI.substring(index + 1);


//        if (method.equals("login")) {
//            //请求登录放行
//            chain.doFilter(httpRequest, httpResponse);
//
//        }

        //加入权限校验
        // 获取前端的token
//        String authorization = httpRequest.getHeader("Authorization");
//
//        if (StringUtils.isNullOrEmpty(authorization)) {
//            throw new CommonException(ResultCode.UNAUTHENTICATED);
//        }

        //前后端约定头信息内容以Bearer+空格+token 形式组成
//        String token = authorization.replace("Bearer ", "");
        //比较并获取claims
//        Claims claims = JwtUtil.parseJWT(token);
//
//        if (claims == null) {
//            throw new CommonException(ResultCode.UNAUTHENTICATED);
//        }
//        String userId = claims.getId();
//        User user = userService.findById(userId);
//
//        Set<Role> roles = user.getRoles();

        //放行
      chain.doFilter(httpRequest, httpResponse);
    }


}

